<template>
  <div class="CloneToper"></div>
  <div class="toper">
    <van-search show-action clear-trigger="always" @clear="onClear" v-model="message" @search="onSearch"
      placeholder="请输入搜索关键字">
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
  </div>
</template>

<script setup lang="ts">
import { onUpdated } from 'vue';
import { ref, watch } from 'vue';

// 相应式的message
const message = ref('');

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  handleSearch: {
    type: String,
    default: ''
  }
});

// 生命周期 更新完成后再去调用 message响应式变量
onUpdated(() => {
  const clearIcon = document.querySelector('.van-field__clear')
  clearIcon?.addEventListener('click', () => {
    message.value = ''
  })
})

// 点击清除按钮后触发事件
function onClear() {
  message.value = ''
}

const emits = defineEmits<{
  (e: 'search', value: string): void;
  (e: 'update:modelValue', value: string): void;
}>();

watch(
  () => props.modelValue,
  () => {
    message.value = props.modelValue;
  }
);

// 创建onSearch的变量方法
const onSearch = () => {
  // 传递给父组件事件名称为search ，事件方法为message.value
  emits('search', message.value);
}
</script>

<style>
.toper {
  width: 100vw;
  gap: 40px;
  position: fixed;
  top: 0;
  z-index: 100;
}

.CloneToper {
  width: 100vw;
  height: 54px;
}

.search {
  background-color: #f5f4f9;
  border-radius: 10px;
}
</style>